package com.startx.core.netty.server.impl;

import java.util.Objects;

import org.apache.log4j.Logger;

import com.startx.core.config.holder.ConfigHolder;
import com.startx.core.netty.pipeline.HttpPipeline;
import com.startx.core.netty.server.Server;
import com.startx.core.system.Colorfulogo;
import com.startx.core.system.config.StartxConfig;
import com.startx.core.system.constants.Constants;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.util.concurrent.DefaultThreadFactory;

public class HttpServer extends Server {

	private static final Logger Log = Logger.getLogger(HttpServer.class);

	private static final StartxConfig config = ConfigHolder.getConfig();
	private static final EventLoopGroup bossGroup = new NioEventLoopGroup(config.getBoss(),new DefaultThreadFactory("boss", true));
	private static final EventLoopGroup workGroup = new NioEventLoopGroup(config.getWorker(),new DefaultThreadFactory("work", true));

	public void run() throws Exception {
		
		try {
			ServerBootstrap b = new ServerBootstrap();
			b.group(bossGroup, workGroup)
					.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
					.childOption(ChannelOption.TCP_NODELAY, true)
					.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
					.childOption(ChannelOption.SO_KEEPALIVE, true).channel(NioServerSocketChannel.class)
					.childHandler(new HttpPipeline());

			// 绑定端口
			int port = config.getPort();
			String ip = config.getIp();
			
			ChannelFuture sync;
			if(Objects.isNull(ip) || Constants.ANY_ADDRESS.equals(ip)) {
				sync = b.bind(port).sync();
				ip = Constants.ANY_ADDRESS;
			} else {
				sync = b.bind(ip,port).sync();
			}
			
			// 打印logo
			Log.info(Colorfulogo.get());
			Log.info("服务已启动，地址："+ip+"	端口： " + port + '.');
			
			//监听服务端端口关闭
			sync.channel().closeFuture().sync();

		} finally {

			bossGroup.shutdownGracefully();
			workGroup.shutdownGracefully();
		}
		
	}
}
